//
//  ZXView.m
//  折线图
//
//  Created by iOS on 16/6/28.
//  Copyright © 2016年 iOS. All rights reserved.
//

#import "CCChartView.h"
@interface CCChartView ()
@property (nonatomic, strong) CAShapeLayer *lineChartLayer;
@property (nonatomic, strong)UIBezierPath * path1;

/** 渐变背景视图 */
@property (nonatomic, strong) UIView *gradientBackgroundView;

@property (strong,nonatomic) UILabel *titleLB;
@property (strong,nonatomic) NSArray *y_titles;
@property (strong,nonatomic) NSArray *x_titles;
@property (strong,nonatomic) NSString *labelText;

@end
@implementation CCChartView

static CGFloat bounceX = 20;
static CGFloat bounceY = 20;
#define kGradientViewHeight  self.height * 0.7

-(instancetype)initWithFrame:(CGRect)frame
                   labelText:(NSString*)labelText
                    x_titles:(NSArray*)x_titles
                    y_titles:(NSArray*)y_titles{
    
    if (self = [super initWithFrame:frame]) {
     //   self.my
        self.backgroundColor = RGBA(255, 255, 255, 1);//LINE_COLOR;//[UIColor lightGrayColor];
        
        _labelText = labelText;
        _x_titles = x_titles;
        _y_titles = y_titles;
        
        [self drawGradientBackgroundView];
        [self createLabelX];
        [self createLabelY];
        [self setLineDash];
        [self setLineDash11];
    }
    return self;
}

- (void)drawRect:(CGRect)rect{
       /*******画出坐标轴********/
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, LINE_WIDTH);
//    CGContextSetRGBStrokeColor(context, 1, 0, 0, 1);
    CGContextSetStrokeColorWithColor(context, TEXT_COLOR.CGColor);
    CGContextMoveToPoint(context, [self maxTextLength], self.gradientBackgroundView.height +self.gradientBackgroundView.y );
//    CGContextAddLineToPoint(context, bounceX, self.gradientBackgroundView.height + self.gradientBackgroundView.y);
    CGContextAddLineToPoint(context,rect.size.width -  bounceX, self.gradientBackgroundView.y + self.gradientBackgroundView.height);
    CGContextStrokePath(context);

}

#pragma mark 添加虚线
- (void)setLineDash{

    for (NSInteger i = 0;i < _y_titles.count; i++ ) {
        
        CAShapeLayer * dashLayer = [CAShapeLayer layer];
        dashLayer.strokeColor = LINE_COLOR.CGColor;
        dashLayer.fillColor = [[UIColor clearColor] CGColor];
        // 默认设置路径宽度为0，使其在起始状态下不显示
        dashLayer.lineWidth = LINE_WIDTH;


        UILabel * label1 = (UILabel*)[self viewWithTag:2000 + i];
        
        UIBezierPath * path = [[UIBezierPath alloc]init];
        path.lineWidth = 1.0;
 
        [path moveToPoint:CGPointMake( 0, label1.center.y - bounceY)];
        [path addLineToPoint:CGPointMake(self.frame.size.width - 2*bounceX,label1.center.y - bounceY)];
        CGFloat dash[] = {10,10};
        [path setLineDash:dash count:2 phase:10];
        [path stroke];
        dashLayer.path = path.CGPath;
        [self.gradientBackgroundView.layer addSublayer:dashLayer];
         }
}

#pragma mark 添加虚线
- (void)setLineDash11{
    
    for (NSInteger i = 0;i < _x_titles.count; i++ ) {
        
        CAShapeLayer * dashLayer = [CAShapeLayer layer];
        dashLayer.strokeColor = LINE_COLOR.CGColor;
        dashLayer.fillColor = [[UIColor clearColor] CGColor];
        // 默认设置路径宽度为0，使其在起始状态下不显示
        dashLayer.lineWidth = LINE_WIDTH;
        
        
        UILabel * label1 = (UILabel*)[self viewWithTag:1000 + i];
        
        UIBezierPath * path = [[UIBezierPath alloc]init];
        path.lineWidth = 1.0;
        
        [path moveToPoint:CGPointMake( label1.center.x - bounceX, self.gradientBackgroundView.height)];
        [path addLineToPoint:CGPointMake(label1.center.x- bounceX,0)];
        CGFloat dash[] = {10,10};
        [path setLineDash:dash count:2 phase:10];
        [path stroke];
        dashLayer.path = path.CGPath;
        [self.gradientBackgroundView.layer addSublayer:dashLayer];
    }
}

#pragma mark 创建x轴的数据
- (void)createLabelX{
    
    NSInteger xTitleCount = _x_titles.count;
    for (NSInteger i = 0; i < xTitleCount; i++) {
        
        CGFloat w = (self.frame.size.width - 2*bounceX)/xTitleCount;
        CGFloat x = w * i + bounceX;
        CGFloat y = self.gradientBackgroundView.y + self.gradientBackgroundView.height + 5;
        CGFloat h = bounceY/2;
        
        UILabel * LabelMonth = [[UILabel alloc]initWithFrame:CGRectMake(x, y, w, h)];
        LabelMonth.tag = 1000 + i;
        LabelMonth.text = _x_titles[i];
        LabelMonth.font = [UIFont systemFontOfSize:10];
        LabelMonth.textAlignment = NSTextAlignmentCenter;

        [self addSubview:LabelMonth];
    }
    
}
#pragma mark 创建y轴数据
#define yLabelFont   10
- (void)createLabelY{
    
    CGFloat labelHeight = bounceY/2.0;
    
    //0的label
    [self creatYLabelWithText:@"0"
                        frame:CGRectMake(0, self.gradientBackgroundView.height + self.gradientBackgroundView.y, [self  maxTextLength], labelHeight)
                          tag:0];
    
    for (NSInteger i = 0; i < _y_titles.count; i++) {
        
        CGRect frame = CGRectMake(0, kGradientViewHeight/_y_titles.count *i + bounceX, [self maxTextLength],labelHeight );
        [self creatYLabelWithText:_y_titles[i]
                            frame:frame
                              tag:2000+i];
    }
}

-(UILabel*)creatYLabelWithText:(NSString*)text frame:(CGRect)frame tag:(NSInteger)tag{

    UILabel *label = [[UILabel alloc] initWithFrame:frame];
    label.text = text;
    label.font = [UIFont systemFontOfSize:yLabelFont];
    label.textAlignment = NSTextAlignmentRight;
    label.tag = tag;
    [self addSubview:label];

    return label;
}
#pragma mark 画折线图
- (void)dravLine{
    
    //x label
    UILabel * label = (UILabel*)[self viewWithTag:1000];
    UIBezierPath * path = [[UIBezierPath alloc]init];
    path.lineWidth = 1.0;
    self.path1 = path;
    UIColor * color = [UIColor greenColor];
    [color set];
    [path moveToPoint:CGPointMake( label.frame.origin.x - bounceX, (600 -arc4random()%600) /600.0 * (self.gradientBackgroundView.frame.size.height - bounceY*2 )  )];

    //创建折现点标记
    NSArray *values = @[@"100",@"1600",@"300",@"2800",@"400",@"2800"];
    
    for (NSInteger i = 1; i< values.count; i++) {
        UILabel * label1 = (UILabel*)[self viewWithTag:1000 + i];
        CGFloat  arc = arc4random()%600;
        [path addLineToPoint:CGPointMake(label1.frame.origin.x - bounceX,  (600 -arc) /600.0 * (self.gradientBackgroundView.frame.size.height - bounceY*2 ) )];
//        UILabel * falglabel = [[UILabel alloc]initWithFrame:CGRectMake(label1.frame.origin.x , (600 -arc) /600.0 * (self.frame.size.height - bounceY*2 )+ bounceY  , 30, 15)];
//        falglabel.backgroundColor = RGBA(200, 200, 200, 1);//[UIColor blueColor];
//        falglabel.tag = 3000+ i;
//        falglabel.text = [NSString stringWithFormat:@"%.1f",arc];
//        falglabel.font = [UIFont systemFontOfSize:8.0];
//        falglabel.textAlignment = NSTextAlignmentCenter;
//        [self addSubview:falglabel];
    }
    // [path stroke];
    
    self.lineChartLayer = [CAShapeLayer layer];
    self.lineChartLayer.path = path.CGPath;
    self.lineChartLayer.strokeColor = [UIColor lightGrayColor].CGColor;
    self.lineChartLayer.fillColor = [[UIColor clearColor] CGColor];
    // 默认设置路径宽度为0，使其在起始状态下不显示
    self.lineChartLayer.lineWidth = 0;
    self.lineChartLayer.lineCap = kCALineCapRound;
    self.lineChartLayer.lineJoin = kCALineJoinRound;
    
    [self.gradientBackgroundView.layer addSublayer:self.lineChartLayer];//直接添加导视图上

}

#pragma mark 渐变的颜色
- (void)drawGradientBackgroundView {
    // 渐变背景视图（不包含坐标轴） self.bounds.size.height - 2*bounceY
    self.gradientBackgroundView = [[UIView alloc] initWithFrame:CGRectMake([self maxTextLength], bounceY, self.bounds.size.width - bounceX - [self maxTextLength], kGradientViewHeight)];
    [self addSubview:self.gradientBackgroundView];
    self.gradientBackgroundView.backgroundColor = [UIColor clearColor];
    
    _titleLB = [UILabel labelWithLableText:_labelText
                                      size:LARGE_FONT
                                 textColor:TEXT_COLOR
                             textAlignment:NSTextAlignmentCenter];
    _titleLB.frame = CGRectMake(0, self.gradientBackgroundView.y + self.gradientBackgroundView.height, self.width, self.height - self.gradientBackgroundView.y - self.gradientBackgroundView.height);
    [self addSubview:_titleLB];
    
    [self maxTextLength];
}




#pragma mark -绘制折线和背景
-(void)showWithAnimation{
    
    [self dravLine];
    
    self.lineChartLayer.lineWidth = 2;
    CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
    pathAnimation.duration = 2;
    pathAnimation.repeatCount = 1;
    pathAnimation.removedOnCompletion = YES;
    pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
    pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
    // 设置动画代理，动画结束时添加一个标签，显示折线终点的信息
    //    pathAnimation.delegate = self;
    [self.lineChartLayer addAnimation:pathAnimation forKey:@"strokeEnd"];

}

- (void)animationDidStart:(CAAnimation *)anim{
    NSLog(@"开始®");
}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    NSLog(@"停止~~~~~~~~");
}

-(CGFloat)maxTextLength{
    
    CGFloat firstTextWidth = [CCUtils WidthForString:_y_titles[0]
                             withSizeOfFont:yLabelFont];
    
    for (int i = 1; i < _y_titles.count; i++) {
        
        CGFloat textWidth = [CCUtils WidthForString:_y_titles[i]
                                          withSizeOfFont:yLabelFont];
        
        if (textWidth >= firstTextWidth)
            firstTextWidth = textWidth;
    }

    return firstTextWidth;
}
@end
